package com.dq.Controller;

import com.dq.Pojo.DTO.PwdEidt;
import com.dq.Pojo.Result;
import com.dq.Pojo.User;
import com.dq.Service.UserService;
import com.dq.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;



@CrossOrigin
@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;

    //通过注册添加用户
    @PostMapping("/toregister")
    public Result toregister(@RequestBody User user){
        //判断用户名是否为空，为空创建用户，反之提示“用户名已被占用”
        User u=userService.findByusername(user.getUsername());
        if (u==null){
            userService.adduser(user);
            return Result.success();
        }else{
            return  Result.error("用户名已被占用");
        }
    }

    //登录，成功到首页，反之重新登陆
    @PostMapping("/loging")
    public  Result<User> loging(@RequestBody User user){

        User u=userService.findByusername(user.getUsername());
        if (u==null){
            return Result.error("用户名错误");
        }
        if(!Md5Util.getMD5String(user.getPassword()).equals(u.getPassword())){
            return Result.error("密码错误");
        }
        if(!user.getRolename().equals(u.getRolename())){
            return Result.error("角色选择错误");
        }
        return Result.success(u);
    }



    //密码修改  由于值传不过来，将参数封装成实体类，进行接收值
    @PutMapping("/editPwd")
    public Result<String> editPwd(@RequestBody PwdEidt pwdEidt){
        User user= userService.findByid(pwdEidt.getUserid());
        String s=Md5Util.getMD5String(pwdEidt.getOldpassword());
        System.out.println(Md5Util.getMD5String(user.getPassword()));
        if (s.equals(user.getPassword())){
            userService.updatePwd(pwdEidt.getUserid(), pwdEidt.getNewpassword());
        }else {
            return Result.error("旧密码错误");
        }
        return Result.success();
    }
    }
